using System;
using System.Collections.Generic;
using System.Text;

namespace Acms.AcmsControls
{
    public class AcmsHttpModule : System.Web.IHttpModule    
    {
        #region IHttpModule Members

        public void Dispose()
        {
        }

        public void Init(System.Web.HttpApplication context)
        {
            context.BeginRequest += new EventHandler(context_BeginRequest);
        }

        void context_BeginRequest(object sender, EventArgs e)
        {
            System.Web.HttpApplication app = sender as System.Web.HttpApplication;
            if (app != null)
            {
                if ((app.Context.Request.AppRelativeCurrentExecutionFilePath.ToLower().EndsWith("/default.aspx") || !System.IO.File.Exists(app.Context.Server.MapPath(app.Context.Request.Path))) && !app.Context.Request.Path.EndsWith(".axd"))
                {
                    string path = app.Context.Request.AppRelativeCurrentExecutionFilePath;
                    if (path.ToLower().EndsWith("/default.aspx"))
                    {
                        path = path.Remove(path.ToLower().IndexOf("/default.aspx"));
                    }
                    else
                    {
                        path = path.Remove(path.LastIndexOf("."));
                    }

                    string templateName = app.Context.Request.QueryString["TF"];
                    string postQueryString = null;

                    //try ToString get from cache
                    if (app.Context.Cache[string.Concat(path, templateName)] != null && app.Context.Cache[string.Concat(path, templateName)] is string)
                    {
                        postQueryString = (string)app.Context.Cache[string.Concat(path, templateName)];
                    }
                    //if not from db
                    if (string.IsNullOrEmpty(postQueryString))
                    {
                        string siteRoot = app.Context.Request.ServerVariables["Server_Name"];
                        if (app.Context.Request.ApplicationPath != "/")
                            siteRoot += app.Context.Request.ApplicationPath;
                        Acms.Bll.Post post = Acms.Bll.Post.GetBySiteUrlAndPostUrl(siteRoot, path);
                        if (post != null)
                        {
                            if (!string.IsNullOrEmpty(templateName))
                            {
                                if (post.GetFile(templateName) == null)
                                {
                                    throw new Acms.Exceptions.TemplateException(string.Format("Could not load template file '{0}' for post '{1}' template '{2}'", templateName, post.Path, post.TemplateName));
                                }
                                else
                                {
                                    postQueryString = post.GetQueryString(templateName);
                                }
                            }
                            else
                            {
                                if (post.GetDefaultFile() == null)
                                {
                                    throw new Acms.Exceptions.TemplateException(string.Format("Could not load template file '{0}' for post '{1}' template '{2}'", templateName, post.Path, post.TemplateName));
                                }
                                else
                                {
                                    postQueryString = post.GetDefaultQueryString();
                                }
                            }
                            app.Context.Cache.Insert(string.Concat(path, templateName), postQueryString, null, DateTime.Now.AddHours(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.BelowNormal, null);
                        }
                        else
                        {
                            throw new Exception(string.Format("Could not find '{0} '{1}'", siteRoot, path));
                        }
                    }

                    if (!string.IsNullOrEmpty(postQueryString))
                    {
                        if (app.Context.Request.QueryString.Keys.Count > 0)
                        {
                            postQueryString = string.Concat(postQueryString, "&", app.Context.Request.QueryString.ToString());
                        }
                        app.Context.RewritePath("~/LoadTemplate.aspx", null, postQueryString, false);
                    }
                }
            }
        }

        #endregion
    }
}
